package com.zm.demo.core.leetcode;

import java.util.List;

/**
 * 反转一个单链表
 * @author zoum
 * @create 2020/1/10 15:46
 */
public class ReverseList {

    public ListNode reverseList(ListNode head) {
        if (head == null){
            return head;
        }
        return reverseList(head, null);
    }

    public ListNode reverseList(ListNode head, ListNode result) {
        if (head == null){
            return result;
        }
        ListNode next = head.next;
        head.next = result;
        result = head;
        return reverseList(next, result);
    }

    public ListNode reverseList1(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode reverse = head;
        ListNode next = head.next;
        reverse.next = null;
        ListNode currentNext = null;
        /**
         * 0，将head赋值给reverse,同时将reverse.next赋值为null，因为这是尾节点。
         * 1. 取出next，并存储在临时变量中
         * 2. 将reverse赋值给next.next
         * 3. 将next赋值给reverse
         * 4. 将 临时变量赋值给next
         * 1->2->3->5->5
         */
        while (next != null){
            currentNext = next.next;
            next.next = reverse;
            reverse = next;
            next = currentNext;
        }
        return reverse;
    }

    public static void main(String[]args){
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);

        new ReverseList().reverseList(head);
    }
}
